<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.teacherId }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
    </el-breadcrumb>
    
    <!--卡片视图区域-->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ currentClass.className }} - 学生管理</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="goBack">返回班级列表</el-button>
        <el-button 
          style="float: right; padding: 3px 0; margin-right: 20px;" 
          type="text"
          @click="addStudentDialogVisible = true">添加学生</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-input placeholder="请输入学生姓名或学号" v-model="queryInfo.query" clearable @clear="getStudentList">
            <el-button slot="append" icon="el-icon-search" @click="getStudentList"></el-button>
          </el-input>
        </el-col>
      </el-row>
      
      <!-- 学生列表 -->
      <el-table :data="studentList" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="studentID" label="学号" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" width="60">
          <template slot-scope="scope">
            {{ scope.row.gender === '男' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="notes" label="备注"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="editStudent(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="removeStudentFromClass(scope.row)">移出班级</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    
    <!-- 添加学生对话框 -->
    <el-dialog title="添加学生" :visible.sync="addStudentDialogVisible" width="40%" @close="addStudentDialogClosed">
      <el-form :model="addStudentForm" :rules="studentFormRules" ref="addStudentFormRef" label-width="100px">
        <el-form-item label="学号" prop="studentID">
          <el-autocomplete
            v-model="addStudentForm.studentID"
            :fetch-suggestions="queryStudentIdAsync"
            placeholder="请输入学生学号"
            :trigger-on-focus="false"
            @select="handleStudentIdSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addStudentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addStudentForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addStudentForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="addStudentForm.notes"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addStudentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addStudentSubmit">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 编辑学生对话框 -->
    <el-dialog title="编辑学生信息" :visible.sync="editStudentDialogVisible" width="40%" @close="editStudentDialogClosed">
      <el-form :model="editStudentForm" :rules="studentFormRules" ref="editStudentFormRef" label-width="100px">
        <el-form-item label="学号" prop="studentID">
          <el-input v-model="editStudentForm.studentID" readonly></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editStudentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editStudentForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editStudentForm.phone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="notes">
          <el-input type="textarea" v-model="editStudentForm.notes"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editStudentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editStudentSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'StudentsManagement',
  data() {
    return {
      teacherId: sessionStorage.getItem('userID'),
      // 当前班级信息
      currentClass: JSON.parse(sessionStorage.getItem('currentClass') || '{"className":"未选择班级"}'),
      // 查询参数
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      // 学生列表
      studentList: [],
      total: 0,
      // 添加学生对话框
      addStudentDialogVisible: false,
      addStudentForm: {
        studentID: '',
        name: '',
        gender: '男',
        phone: '',
        notes: '',
        className: ''
      },
      // 编辑学生对话框
      editStudentDialogVisible: false,
      editStudentForm: {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        className: ''
      },
      // 表单验证规则
      studentFormRules: {
        studentID: [
          { required: true, message: '请输入学生学号', trigger: 'blur' },
          { min: 8, max: 20, message: '学号长度在 8 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (!this.currentClass.className || this.currentClass.className === '未选择班级') {
      this.$message.warning('请先选择班级')
      this.$router.push('/manage/' + this.teacherId + '/class/my-classes')
      return
    }
    this.getStudentList()
  },
  methods: {
    // 获取学生列表
    async getStudentList() {
      try {
        const { data: res } = await this.$http.get(this.$http + '/student/findByClassName', {
          params: {
            className: this.currentClass.className,
            query: this.queryInfo.query,
            pageNum: this.queryInfo.pageNum,
            pageSize: this.queryInfo.pageSize
          }
        })
        if (res.code === 200) {
          this.studentList = res.data
          this.total = res.total || res.data.length
        } else {
          this.$message.error(res.message || '获取学生列表失败')
        }
      } catch (error) {
        console.error('获取学生列表失败', error)
        this.$message.error('获取学生列表失败')
      }
    },
    
    // 处理每页显示条数变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getStudentList()
    },
    
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getStudentList()
    },
    
    // 返回班级列表页面
    goBack() {
      this.$router.push('/manage/' + this.teacherId + '/class/my-classes')
    },
    
    // 添加学生对话框关闭
    addStudentDialogClosed() {
      this.$refs.addStudentFormRef.resetFields()
    },
    
    // 编辑学生对话框关闭
    editStudentDialogClosed() {
      this.$refs.editStudentFormRef.resetFields()
    },
    
    // 提交添加学生表单
    addStudentSubmit() {
      this.$refs.addStudentFormRef.validate(async valid => {
        if (!valid) return
        // 设置班级名称
        this.addStudentForm.className = this.currentClass.className
        try {
          // 创建学生
          const { data: res } = await this.$http.post(this.$http + '/student/insert', this.addStudentForm)
          if (res.code === 200) {
            // 创建用户账号
            const userForm = {
              id: this.addStudentForm.studentID,
              password: '123456', // 默认密码
              role: 2 // 学生角色
            }
            await this.$http.post(this.$http + '/user/insert', userForm)
            
            this.$message.success('添加学生成功')
            this.addStudentDialogVisible = false
            this.getStudentList()
          } else {
            this.$message.error(res.message || '添加学生失败')
          }
        } catch (error) {
          console.error('添加学生失败', error)
          this.$message.error('添加学生失败')
        }
      })
    },
    
    // 编辑学生
    editStudent(row) {
      this.editStudentForm = { ...row }
      this.editStudentDialogVisible = true
    },
    
    // 提交编辑学生表单
    editStudentSubmit() {
      this.$refs.editStudentFormRef.validate(async valid => {
        if (!valid) return
        try {
          const { data: res } = await this.$http.post(this.$http + '/student/update', this.editStudentForm)
          if (res.code === 200) {
            this.$message.success('更新学生信息成功')
            this.editStudentDialogVisible = false
            this.getStudentList()
          } else {
            this.$message.error(res.message || '更新学生信息失败')
          }
        } catch (error) {
          console.error('更新学生信息失败', error)
          this.$message.error('更新学生信息失败')
        }
      })
    },
    
    // 将学生从班级中移除
    removeStudentFromClass(row) {
      this.$confirm('确认将学生从班级中移除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 修改学生记录，将班级设为空
          const studentData = { ...row, className: '' }
          const { data: res } = await this.$http.post(this.$http + '/student/update', studentData)
          if (res.code === 200) {
            this.$message.success('已将学生从班级中移除')
            // 更新班级学生数量
            const classData = {
              className: this.currentClass.className,
              teacherId: this.currentClass.teacherId,
              numberOfStudents: this.currentClass.numberOfStudents - 1
            }
            await this.$http.post(this.$http + '/class/update', classData)
            // 本地更新班级学生数量
            this.currentClass.numberOfStudents -= 1
            sessionStorage.setItem('currentClass', JSON.stringify(this.currentClass))
            this.getStudentList()
          } else {
            this.$message.error(res.message || '移除学生失败')
          }
        } catch (error) {
          console.error('移除学生失败', error)
          this.$message.error('移除学生失败')
        }
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    // 学号自动完成
    async queryStudentIdAsync(queryString, cb) {
      if (queryString.trim() === '') {
        cb([])
        return
      }
      
      try {
        const { data: res } = await this.$http.get('/student/searchByStudentIdPrefix', {
          params: { prefix: queryString }
        })
        
        if (res.code === 200) {
          const studentList = res.data || []
          const suggestions = studentList.map(student => ({
            value: student.studentID,
            student: student,
            label: `${student.studentID} - ${student.name || ''}`
          }))
          cb(suggestions)
        } else {
          cb([])
        }
      } catch (error) {
        console.error('获取学生列表失败', error)
        cb([])
      }
    },
    
    // 学号选中事件
    handleStudentIdSelect(item) {
      if (item && item.student) {
        this.addStudentForm.studentID = item.value
        this.addStudentForm.name = item.student.name || ''
        this.addStudentForm.gender = item.student.gender || '男'
        this.addStudentForm.phone = item.student.phone || ''
        this.addStudentForm.notes = item.student.notes || ''
      }
    },
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
</style>
